package com.fangwei.utilsLibrary.utils;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * SD卡的相关工具类
 * Created by Administrator on 2017/8/25.
 */

public class SDCardUtil {

    private SDCardUtil(){
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 判断sd卡是否可用
     * @return true 可用 false 不可用
     */
    public static boolean isSDCardEnable(){
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 获取sd卡的路径
     * @return 一般是/storage/emulated/0/
     */
    public static String getSDCardPath(){
       if(!isSDCardEnable()) return null;
        String cmd = "cat /proc/mounts";
        Runtime run = Runtime.getRuntime();
        BufferedReader bufferedReader = null;
        try {
            Process p = run.exec(cmd);
            bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream())));
            String lineStr;
            while ((lineStr = bufferedReader.readLine()) != null){
                if(lineStr.contains("sdcard") && lineStr.contains(".android_secure")){
                    String[] strArray = lineStr.split(" ");
                    if(strArray.length >= 5 ){
                       return strArray[1].replace("/.android_secure","") + File.separator;
                    }
                }
                if(p.waitFor() != 0 && p.exitValue() == 1){
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

        }
        return Environment.getExternalStorageDirectory().getPath() + File.separator;
    }

    /**
     * 获取SD卡data路径
     * @return
     */
    public static String getDataPath(){
        if(!isSDCardEnable()) return null;
        return Environment.getExternalStorageDirectory().getPath()+ File.separator + "data"+ File.separator;
    }

    /**
     * 获取sd卡的剩余空间
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static String getFreeSpace(){
        if(!isSDCardEnable()) return null;
        StatFs statFs = new StatFs(getSDCardPath());
        long blockSize,availableBlocks;
        availableBlocks = statFs.getAvailableBlocksLong();
        blockSize = statFs.getBlockSizeLong();
        return ConvertUtil.byte2FitMemorySize(availableBlocks * blockSize);
    }



}
